
package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.sys.core.properties.SysConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.MessageType;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.core.util.WebChatUtil;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wxApi")
public class WxapiController extends BaseController {
    @Resource
    private BtyBxdService btyBxdService;
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private MeiTuanService meiTuanService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private BtyArchivesService btyArchivesService;
    @Resource
    private WebChatService webChatService;
    @Resource
    private DeptService deptService;
    @Resource
    private TaskService taskService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private ProjectService projectService;
    @Resource
    private SysConfig sysConfig;

    public static final String TOKEN = "bty";

    @RequestMapping("")
    private void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上，GET请求携带参数
            String signature = request.getParameter("signature");// 微信加密签名（token、timestamp、nonce。）
            String timestamp = request.getParameter("timestamp");// 时间戳
            String nonce = request.getParameter("nonce");// 随机数
            String echostr = request.getParameter("echostr");// 随机字符串
            // 将token、timestamp、nonce三个参数进行字典序排序
            String[] params = new String[]{TOKEN, timestamp, nonce};
            Arrays.sort(params);
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            String clearText = params[0] + params[1] + params[2];
            String algorithm = "SHA-1";
            String sign = new String(
                    Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
            // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if (signature.equals(sign)) {
                response.getWriter().print(echostr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO 消息的接收、处理、响应
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名（token、timestamp、nonce。）
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        //确认此次GET请求来自微信服务器，原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
        if (!WebChatUtil.checkSignature(signature, timestamp, nonce)) {
            //消息不可靠，直接返回
            response.getWriter().write("");
            return;
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/xml");
            //调用parseXml方法解析请求消息
            Map<String, String> map = MessageType.parseXml(request, response);
            String MsgType = map.get("MsgType");
            String content = map.get("Content") == null ? "" : map.get("Content");
            String openid = map.get("FromUserName");
            StringBuilder sb = new StringBuilder();
//            Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
//            String accessToken = "";
//            if (ToolUtil.isNotEmpty(dict)) {
//                accessToken = dict.getName();
//            }
            int num = 0;
            int flag = 0;
            //获取姓名和银行卡号匹配供应商
            if (content.contains("#")) {
                String xm = content.split("[#]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String yhk = content.split("[#]")[1].replaceAll("\\s*", "");
                List<BtyBxda> bxdaList = btyBxdaService.list(new QueryWrapper<BtyBxda>().eq("xm", xm).eq("yhk", yhk));
                //绑定供应商的openid
                if (bxdaList.size() > 0) {
                    //绑定之前查询是否已经绑定
                    List<BtyBxda> bxdaLists = btyBxdaService.list(new QueryWrapper<BtyBxda>().eq("openid", openid));
                    if (bxdaLists.size() > 0) {
                        flag = 1;
                    } else {
                        num = btyBxdaService.setOpenid(openid, xm, yhk);
                    }
                }
                // }
//            //通过openid获取昵称
//            emplate restTemplate = new RestTemplate();
//            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
//            //String url = "https://api.weixin.qq.com/cgi-bin/user/info";
//            String userInfo = restTemplate.getForObject(url, String.class);
//            JSONObject jsonObject = JSONObject.parseObject(userInfo);
//            if(ToolUtil.isNotEmpty(jsonObject)){
//               String nickName = jsonObject.get("nickname")==null?"":jsonObject.get("nickname").toString();
//               //保存openid和微信昵称
//               BtyWx btyWx1=btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid",openid));
//               if(ToolUtil.isEmpty(btyWx1)){
//                   BtyWx btyWx=new BtyWx();
//                   btyWx.setOpenid(openid);
//                   btyWx.setNickname(nickName);
//                   btyWxMapper.insert(btyWx);
//               }else{
//                   String nickname=btyWx1.getNickname();
//                   if(!nickname.equals(nickName)){
//                   btyWx1.setNickname(nickName);
//                   btyWxMapper.updateById(btyWx1);
//                   }
//               }
//            }
//            if(flag==1){
//
//            }
                if (num > 0) {
                    sb.append("绑定成功!请输入日期-日期查询例如20200801-20200805!");
                } else {
                    if (flag == 1) {
                        sb.append("已绑定成功,无须重复绑定!请输入日期-日期查询例如20200801-20200805!");
                    } else {
                        sb.append("绑定失败!姓名或者银行卡有误,请重新输入!");
                    }
                }
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }
            }
            //通过日期查询报销单相关数据
            else if (content.contains("-")) {
                String beginTime = content.split("[-]")[0].replaceAll("\\s*", "");
                String endTime = content.split("[-]")[1].replaceAll("\\s*", "");
                endTime = endTime + " 23:59:59";
                List<BtyBxd> listZje = btyBxdService.sumJe(openid, beginTime, endTime);
                List<BtyBxd> list = btyBxdService.sumZcje(openid, beginTime, endTime);
                List<BtyBxd> listWbx = btyBxdService.sumWbxje(openid, beginTime, endTime);
                DecimalFormat format = new DecimalFormat("0.00");
                if (ToolUtil.isNotEmpty(listZje)) {
                    String xm1 = listZje.get(0).getBxr();
                    String sumJe = format.format(new BigDecimal(listZje.get(0).getSumZcje()));
                    sb.append(xm1).append("总金额:").append(sumJe).append("\r\n");
                    if (ToolUtil.isNotEmpty(list)) {
                        String xm2 = list.get(0).getBxr();
                        String sumZcje = format.format(new BigDecimal(list.get(0).getSumZcje()));
                        String sumWbxje = listWbx == null | listWbx.size() == 0 ? "0" : format.format(new BigDecimal(listWbx.get(0).getSumZcje()));
                        sb.append(xm2).append("已报销:").append(sumZcje).append("\r\n");
                        sb.append(xm2).append("未报销:").append(sumWbxje).append("\r\n");
                        for (int i = 0; i < list.size(); i++) {
                            String dm = list.get(i).getDm();
                            //String xm=list.get(i).getBxr();
                            String zcje = format.format(new BigDecimal(list.get(i).getZcje()));
                            sb.append(dm).append("已报销金额:").append(zcje).append("\r\n");
                        }
                    } else {
                        sb.append(xm1).append("已报销:0").append("\r\n");
                    }

                    if (ToolUtil.isNotEmpty(listWbx)) {
                        for (int i = 0; i < listWbx.size(); i++) {
                            String dm = listWbx.get(i).getDm();
                            String zcje = listWbx.get(i).getZcje() == null ? "0" : format.format(new BigDecimal(listWbx.get(i).getZcje()));
                            sb.append(dm).append("未报销金额:").append(zcje).append("\r\n");
                        }
                    } else {
                        sb.append(xm1).append("未报销:0").append("\r\n");
                    }
                } else {
                    sb.append("暂无数据!");
                }

            }
            //通过门店号查询美团消费相关数据
            else if (content.contains("mt")) {
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
                String beginTime=df.format(new Date());
                String endTime = beginTime + " 23:59:59";
                //获取门店编号
                String yaoMa=content.substring(content.indexOf("mt")+2);
                List<MeiTuan>meiTuanList=meiTuanService.list(new QueryWrapper<MeiTuan>().eq("mm",yaoMa)
                .ge("sj",beginTime).le("sj",endTime));
                DecimalFormat format = new DecimalFormat("0.00");
                if (ToolUtil.isNotEmpty(meiTuanList)) {
                    for (int i = 0; i < meiTuanList.size(); i++) {
                        String xm = meiTuanList.get(i).getXm()==null?"":meiTuanList.get(i).getXm();
                        String phone = meiTuanList.get(i).getSjh();
                        String xf =meiTuanList.get(i).getXf()==null?"0":format.format(new BigDecimal(meiTuanList.get(i).getXf()));
                        sb.append(xm).append(phone).append("已消费金额:").append(xf).append("\r\n");
                    }
                } else {
                    sb.append("暂无数据!");
                }
            }
            //通过姓名和手机号绑定钉钉id
            else if (content.contains("*")) {
                String xm = content.split("[*]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String phone = content.split("[*]")[1].replaceAll("\\s*", "");
                List<BtyArchives> btyArchivesList = btyArchivesService.list(new QueryWrapper<BtyArchives>().eq("xm", xm).eq("tel", phone));
//                //绑定用户的钉钉id
                if (btyArchivesList.size() > 0) {
                    //绑定之前查询是否已经绑定
                    List<BtyWx> wxList = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid));
                    if (wxList.size() > 0) {
                        List<BtyWx> wxLists = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid).eq("phone", phone));
                        if (wxLists.size() > 0) {
                            flag = 2;
                        } else {
                            BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                            btyWx.setPhone(phone);
                            btyWx.setDingId(btyArchivesList.get(0).getBh());
                            btyWx.setName(btyArchivesList.get(0).getXm());
                            btyWx.setShopName(btyArchivesList.get(0).getDm());
                            btyWx.setRegionOne(btyArchivesList.get(0).getQy());
                            btyWx.setRegionTwo(btyArchivesList.get(0).getEqy());
                            btyWx.setPost(btyArchivesList.get(0).getZw());
                            btyWxMapper.updateById(btyWx);
                            num = 3;
                        }
                    } else {
                        BtyWx btyWx = new BtyWx();
                        btyWx.setOpenid(openid);
                        btyWx.setId(UUIDUtils.getId());
                        btyWx.setPhone(phone);
                        btyWx.setDingId(btyArchivesList.get(0).getBh());
                        btyWx.setName(btyArchivesList.get(0).getXm());
                        btyWx.setShopName(btyArchivesList.get(0).getDm());
                        btyWx.setRegionOne(btyArchivesList.get(0).getQy());
                        btyWx.setRegionTwo(btyArchivesList.get(0).getEqy());
                        btyWx.setPost(btyArchivesList.get(0).getZw());
                        num = btyWxMapper.insert(btyWx);
                    }
                }
                if (num > 0) {
                    //通过openid获取姓名
                    BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                    String name = "";
                    if (ToolUtil.isNotEmpty(btyWx)) {
                        name = btyWx.getName();
                    }
                    sb.append("绑定成功!欢迎" + name + "回家!【半天妖】*^_^*");
                } else {
                    if (flag == 2) {
                        sb.append("已绑定成功,无须重复绑定!");
                    } else {
                        sb.append("绑定失败!姓名或者手机号有误,请重新输入!");
                    }
                }
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }

            }
            //通过姓名和手机号，部门绑定部门
            else if (content.contains("@")) {
                String xm = content.split("[@]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String phone = content.split("[@]")[1].replaceAll("\\s*", "");
                String bm = content.split("[@]")[2].replaceAll("\\s*", "");
                //查询部门是否存在
                Long deptId = null;
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("simple_name", bm));
                if (ToolUtil.isNotEmpty(dept)) {
                    deptId = dept.getDeptId();
                } else {
                    dept = new Dept();
                    dept.setDeptId(UUIDUtils.getId());
                    dept.setPid(24L);
                    dept.setPids("[0],[24],");
                    dept.setSimpleName(bm);
                    Boolean flags = deptService.save(dept);
                    if (flags == true) {
                        deptId = dept.getDeptId();
                    }
                }
                // List<BtyArchives> btyArchivesList = btyArchivesService.list(new QueryWrapper<BtyArchives>().eq("xm", xm).eq("tel", phone));
                //绑定之前查询是否已经绑定
                List<BtyWx> wxList = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid));
                if (wxList.size() > 0) {
                    List<BtyWx> wxLists = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid).eq("phone", phone)
                            .eq("name", xm).eq("dept_id", deptId));
                    if (wxLists.size() > 0) {
                        flag = 2;
                    } else {
                        BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                        btyWx.setPhone(phone);
                        btyWx.setName(xm);
                        btyWx.setDeptId(deptId);
                        btyWxMapper.updateById(btyWx);
                        num = 3;
                    }
                } else {
                    BtyWx btyWx = new BtyWx();
                    btyWx.setOpenid(openid);
                    btyWx.setId(UUIDUtils.getId());
                    btyWx.setPhone(phone);
                    btyWx.setName(xm);
                    btyWx.setDeptId(deptId);
                    num = btyWxMapper.insert(btyWx);
                }
                if (num > 0) {
                    BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                    String name = "";
                    if (ToolUtil.isNotEmpty(btyWx)) {
                        name = btyWx.getName();
                    }
                    sb.append("绑定成功!欢迎" + name + "回家!【半天妖】*^_^*");
                } else {
                    if (flag == 2) {
                        sb.append("已绑定成功,无须重复绑定!");
                    } else {
                        sb.append("绑定失败!姓名或者手机号有误,请重新输入!");
                    }
                }
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }

            } else {
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }
            }


            //通过发送人openID和店名,确定可乐机安装状态
            if (openid.equals("oM18PwWQsdIP3QEKcWejL1tF3X8s") && content.contains("已完成")) {

                String name = content.split("已完成")[0].replaceAll("\\s*", "");
                //根据店名查询ProID
                Integer proId = taskService.selectProId(name);

                //查询此任务是否已存在
                int count = taskService.selectCount(proId);
                if (count == 0) {

                    //任务状态表
                    TaskStatus status = new TaskStatus();
                    status.setProId(proId);
                    status.setStatus(1);
                    status.setTaskId(20);//可乐机到店安装完成

                    //流程明细表
                    TaskFlow taskFlow = new TaskFlow();
                    taskFlow.setProId(proId);
                    taskFlow.setTaskId(20);
                    taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
//                        taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
                        taskFlow.setCreateTime(new Date());

                    //新增任务相关表数据
                    taskService.insertRent(status, taskFlow);

/////////////////////
                    //向督导,营运经理,营运总监推送消息
                    String[] str = {"可乐机状态","可乐机", DateUtil.getNow(),name + "可乐机已安装"};
                    //发送模板
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(name,null, str);

                    Map<String, String> openidMap = projectService.selectDd(proId);
                    //督导
                    String dd = openidMap.get("dd");
                    //营运经理
                    String yyjl = openidMap.get("yyjl");
                    //营运总监
                    String yyzj = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
                    String[] openids = new String[]{dd, yyjl, yyzj};

                    //推送消息
                    weChatSendTempMsgService.sendmsg(openids,null,tempObj);

////////////////////

                    num = 2;
                    if (num > 0){
                        sb.append(name + "可乐机安装完成,*^_^*");
                    }

                }

            }


            String xml = "";//处理输入消息，返回结果的xml
            if (MessageType.REQ_MESSAGE_TYPE_EVENT.equals(MsgType)) {
                xml = webChatService.parseEvent(map);
            } else {
                xml = webChatService.parseMessage(map, sb.toString());
            }
            //返回封装的xml
            //System.out.println(xml);
            response.getWriter().write(xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


